﻿using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace Tutorial_Utils
{
	public class TimerManager : IDisposable
	{
		private readonly Dictionary<string, PerfTimer> stopWatches = new Dictionary<string, PerfTimer>();

		public PerfTimer this[string swName]
		{
			get
			{
				if (!stopWatches.ContainsKey(swName))
				{
					stopWatches.Add(swName, new PerfTimer());
				}
					
				return stopWatches[swName];
			}
		}

		#region IDisposable Members

		public void Dispose()
		{
			foreach (PerfTimer timer in stopWatches.Values)
			{
				if (timer != null)
				{
					timer.Stop();
				}
			}
		}

		#endregion
	}

	public class PerfTimer
	{
		private readonly Stopwatch stopWacth = new Stopwatch();
		private bool resetBeforeStart;
		private int precision;

		public PerfTimer()
		{
			resetBeforeStart = false;
			precision = 4;
		}

		public double Duration
		{
			get { return Math.Round(stopWacth.Elapsed.TotalMilliseconds / 1000, precision, MidpointRounding.AwayFromZero); }
		}

		public int Precision
		{
			get { return precision; }
			set { precision = value; }
		}

		public bool ResetBeforeStart
		{
			get { return resetBeforeStart; }
			set { resetBeforeStart = value; }
		}

		public void Start()
		{
			if (resetBeforeStart)
			{
				Reset();
			}

			stopWacth.Start();
		}

		public void Stop()
		{
			stopWacth.Stop();
		}

		public void Reset()
		{
			stopWacth.Reset();
		}
	}
}
